package com.guijq.codesegment.propertydescriptor;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;

/**
 * @author yangjf
 * @version 0.1.0
 * @time 2018/8/1/001
 */

/**
 * 　反射可以操作各种类的属性，而内省只是通过反射来操作JavaBean的属性
 　　内省设置属性值肯定会调用seter方法，反射可以不用
 */

public class PropertyDescriptorTest {
    public static void setProperty(Object obj, String property)throws Exception{

        PropertyDescriptor propDesc=new PropertyDescriptor(property, obj.getClass());
        Method methodSetUserName=propDesc.getWriteMethod();
        methodSetUserName.invoke(obj, "wong");
    }

    public static Object getProperty(Object userInfo,String property)throws Exception{
        PropertyDescriptor proDescriptor =new PropertyDescriptor(property, userInfo.getClass());
        Method methodGetUserName=proDescriptor.getReadMethod();
        Object objUserName=methodGetUserName.invoke(userInfo);
        System.out.println("get property:"+objUserName.toString());
        return objUserName;
    }

    public static void main(String[] args) {
        UserInfo userInfo = new UserInfo();
        try {
            setProperty(userInfo, "name");
            getProperty(userInfo, "name");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
